// 文件名称：communication.js
// 完整保存路径：miniprogram/pages/communication/communication.js
// 功能说明：医生交流页面逻辑控制
// 使用说明：处理医患交流、咨询问题、医生回复等功能

const { getToken } = require('../../utils/auth.js');

const app = getApp();

Page({
  data: {
    currentTab: 0,
    tabs: [
      { id: 0, name: '我的咨询', type: 'my_consults' },
      { id: 1, name: '医生回复', type: 'doctor_replies' },
      { id: 2, name: '新咨询', type: 'new_consult' }
    ],
    consults: [],
    loading: false,
    hasMore: true,
    page: 1,
    perPage: 10,
    refreshing: false,
    
    // 新咨询表单数据
    newConsult: {
      title: '',
      content: '',
      category: '',
      images: [],
      priority: 'normal'
    },
    
    // 分类选项
    categories: [
      { value: 'vision_check', label: '视力检查' },
      { value: 'intervention', label: '干预咨询' },
      { value: 'symptoms', label: '症状询问' },
      { value: 'treatment', label: '治疗方案' },
      { value: 'prevention', label: '预防建议' },
      { value: 'other', label: '其他问题' }
    ],
    
    // 优先级选项
    priorities: [
      { value: 'normal', label: '普通' },
      { value: 'urgent', label: '紧急' },
      { value: 'emergency', label: '非常紧急' }
    ],
    
    showCategoryPicker: false,
    showPriorityPicker: false,
    categoryIndex: -1,
    priorityIndex: 0  // 默认选择"普通"优先级
  },

  onLoad() {
    console.log('医生交流页面加载');
    this.loadConsults();
  },

  onShow() {
    // 页面显示时刷新数据
    this.refreshData();
  },

  onPullDownRefresh() {
    this.refreshData();
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreConsults();
    }
  },

  /**
   * 切换标签页
   */
  onTabChange(e) {
    const tabId = e.currentTarget.dataset.id;
    if (tabId === this.data.currentTab) return;
    
    this.setData({
      currentTab: tabId,
      consults: [],
      page: 1,
      hasMore: true
    });
    
    this.loadConsults();
  },

  /**
   * 加载咨询列表
   */
  async loadConsults() {
    if (this.data.loading) return;
    
    try {
      this.setData({ loading: true });
      
      const token = getToken();
      if (!token) {
        wx.showToast({
          title: '请先登录',
          icon: 'error'
        });
        return;
      }
      
      const currentTab = this.data.tabs[this.data.currentTab];
      const params = {
        page: this.data.page,
        per_page: this.data.perPage,
        type: currentTab.type
      };
      
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.apiBaseUrl}/communication/consults`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          },
          data: params,
          success: resolve,
          fail: reject
        });
      });
      
      if (response.statusCode === 200 && response.data.success) {
        const result = response.data.data;
        const { mapMediaUrls } = require('../../utils/media');
        // 规范化图片字段（如存在）
        const mapped = (result.consults || []).map(c => ({
          ...c,
            images: mapMediaUrls(c.images),
            reply_images: mapMediaUrls(c.reply_images)
        }));

        this.setData({
          consults: this.data.page === 1 ? mapped : [...this.data.consults, ...mapped],
          hasMore: result.pagination.has_next,
          loading: false,
          refreshing: false
        });
        wx.stopPullDownRefresh();
      } else {
        throw new Error(response.data.message || '获取咨询记录失败');
      }
      
    } catch (error) {
      console.error('加载咨询记录失败:', error);
      this.setData({
        loading: false,
        refreshing: false
      });
      
      wx.stopPullDownRefresh();
      wx.showToast({
        title: error.message || '加载咨询记录失败',
        icon: 'error'
      });
    }
  },

  /**
   * 加载更多咨询
   */
  loadMoreConsults() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        page: this.data.page + 1
      });
      this.loadConsults();
    }
  },

  /**
   * 刷新数据
   */
  async refreshData() {
    this.setData({
      refreshing: true,
      page: 1,
      hasMore: true
    });
    
    await this.loadConsults();
  },

  /**
   * 新咨询表单输入处理
   */
  onTitleInput(e) {
    this.setData({
      'newConsult.title': e.detail.value
    });
  },

  onContentInput(e) {
    this.setData({
      'newConsult.content': e.detail.value
    });
  },

  /**
   * 选择分类
   */
  onCategoryChange(e) {
    const index = e.detail.value;
    this.setData({
      'newConsult.category': this.data.categories[index].value,
      categoryIndex: index
    });
  },

  /**
   * 选择优先级
   */
  onPriorityChange(e) {
    const index = e.detail.value;
    this.setData({
      'newConsult.priority': this.data.priorities[index].value,
      priorityIndex: index
    });
  },

  /**
   * 选择图片
   */
  chooseImages() {
    const maxCount = 4 - this.data.newConsult.images.length;
    if (maxCount <= 0) {
      wx.showToast({
        title: '最多只能上传4张图片',
        icon: 'none'
      });
      return;
    }

    wx.chooseImage({
      count: maxCount,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: (res) => {
        console.log('选择图片成功:', res);
        
        // 检查每个文件的大小
        const validImages = [];
        const promises = res.tempFilePaths.map(path => {
          return new Promise((resolve) => {
            wx.getFileInfo({
              filePath: path,
              success: (fileInfo) => {
                console.log(`图片信息: ${path}, 大小: ${fileInfo.size} bytes`);
                if (fileInfo.size > 70) { // 70字节是微信开发工具常见的损坏文件大小
                  validImages.push(path);
                } else {
                  console.warn(`图片文件过小，跳过: ${path}, 大小: ${fileInfo.size} bytes`);
                }
                resolve();
              },
              fail: (error) => {
                console.error(`获取文件信息失败: ${path}`, error);
                resolve();
              }
            });
          });
        });
        
        Promise.all(promises).then(() => {
          if (validImages.length > 0) {
            this.setData({
              'newConsult.images': [...this.data.newConsult.images, ...validImages]
            });
          } else {
            wx.showToast({
              title: '所选图片文件异常，请重新选择',
              icon: 'none'
            });
          }
        });
      },
      fail: (error) => {
        console.error('选择图片失败:', error);
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  },

  /**
   * 删除图片
   */
  deleteImage(e) {
    const index = e.currentTarget.dataset.index;
    const images = this.data.newConsult.images;
    images.splice(index, 1);
    this.setData({
      'newConsult.images': images
    });
  },

  /**
   * 预览图片
   */
  previewImage(e) {
    const index = e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.newConsult.images[index],
      urls: this.data.newConsult.images
    });
  },

  /**
   * 提交新咨询
   */
  async submitConsult() {
    const { title, content, category, priority } = this.data.newConsult;
    
    // 表单验证
    if (!title.trim()) {
      wx.showToast({
        title: '请输入咨询标题',
        icon: 'none'
      });
      return;
    }
    
    if (!content.trim()) {
      wx.showToast({
        title: '请输入咨询内容',
        icon: 'none'
      });
      return;
    }
    
    if (!category) {
      wx.showToast({
        title: '请选择咨询分类',
        icon: 'none'
      });
      return;
    }
    
    try {
      wx.showLoading({ title: '提交中...' });
      
      const token = getToken();
      if (!token) {
        wx.showToast({
          title: '请先登录',
          icon: 'error'
        });
        return;
      }
      
      // 如果有图片，先上传图片
      let imageUrls = [];
      if (this.data.newConsult.images.length > 0) {
        try {
          imageUrls = await this.uploadImages(this.data.newConsult.images);
        } catch (error) {
          wx.hideLoading();
          console.error('图片上传失败:', error);
          
          // 询问用户是否继续提交（不包含图片）
          const res = await new Promise(resolve => {
            wx.showModal({
              title: '图片上传失败',
              content: '是否继续提交咨询（不包含图片）？',
              success: resolve
            });
          });
          
          if (!res.confirm) {
            return; // 用户取消，不继续提交
          }
          
          // 继续提交，但不包含图片
          imageUrls = [];
          wx.showLoading({ title: '提交中...' });
        }
      }
      
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: `${app.globalData.apiBaseUrl}/communication/consults`,
          method: 'POST',
          header: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          data: {
            title: title.trim(),
            content: content.trim(),
            category,
            priority,
            images: imageUrls
          },
          success: resolve,
          fail: reject
        });
      });
      
      wx.hideLoading();
      
      if (response.statusCode === 200 && response.data.success) {
        wx.showToast({
          title: '咨询提交成功',
          icon: 'success'
        });
        
        // 清空表单
        this.setData({
          newConsult: {
            title: '',
            content: '',
            category: '',
            images: [],
            priority: 'normal'
          }
        });
        
        // 切换到我的咨询标签并刷新
        this.setData({ currentTab: 0 });
        this.refreshData();
        
      } else {
        throw new Error(response.data.message || '提交咨询失败');
      }
      
    } catch (error) {
      wx.hideLoading();
      console.error('提交咨询失败:', error);
      wx.showToast({
        title: error.message || '提交咨询失败',
        icon: 'error'
      });
    }
  },

  /**
   * 上传图片
   */
  async uploadImages(imagePaths) {
    const token = getToken();
    
    // 先检查所有图片的文件大小
    for (const path of imagePaths) {
      try {
        const fileInfo = await new Promise((resolve, reject) => {
          wx.getFileInfo({
            filePath: path,
            success: resolve,
            fail: reject
          });
        });
        
        console.log(`准备上传图片: ${path}, 大小: ${fileInfo.size} bytes`);
        
        if (fileInfo.size < 100) { // 小于100字节的图片可能有问题
          console.error(`图片文件过小: ${path}, 大小: ${fileInfo.size} bytes`);
          throw new Error(`图片文件异常，大小仅 ${fileInfo.size} 字节。这可能是微信开发者工具的问题，建议尝试其他图片或使用真机调试。`);
        }
      } catch (error) {
        console.error('获取文件信息失败:', error);
        throw new Error('图片文件信息获取失败');
      }
    }
    
    const uploadPromises = imagePaths.map(path => new Promise((resolve, reject) => {
      wx.uploadFile({
        url: `${app.globalData.apiBaseUrl}/upload/image?category=communication`,
        filePath: path,
        name: 'image',
        formData: { category: 'communication' },
        header: { 'Authorization': `Bearer ${token}` },
        success: (res) => {
          try {
            const data = JSON.parse(res.data);
            if (data.success) resolve(data.data.url);
            else reject(new Error(data.message || '上传失败'));
          } catch (e) { reject(new Error('上传响应解析失败')); }
        },
        fail: (error) => reject(new Error(error.errMsg || '上传请求失败'))
      });
    }));

    return Promise.all(uploadPromises);
  },

  /**
   * 查看咨询详情
   */
  viewConsultDetail(e) {
    const consultId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/communication/detail/detail?id=${consultId}`
    });
  },

  /**
   * 获取分类显示名称
   */
  getCategoryLabel(value) {
    const category = this.data.categories.find(cat => cat.value === value);
    return category ? category.label : value;
  },

  /**
   * 获取优先级显示名称
   */
  getPriorityLabel(value) {
    const priority = this.data.priorities.find(pri => pri.value === value);
    return priority ? priority.label : value;
  },

  /**
   * 格式化时间
   */
  formatTime(timestamp) {
    if (!timestamp) return '';
    
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    
    // 小于1分钟
    if (diff < 60000) {
      return '刚刚';
    }
    
    // 小于1小时
    if (diff < 3600000) {
      return `${Math.floor(diff / 60000)}分钟前`;
    }
    
    // 小于24小时
    if (diff < 86400000) {
      return `${Math.floor(diff / 3600000)}小时前`;
    }
    
    // 小于30天
    if (diff < 2592000000) {
      return `${Math.floor(diff / 86400000)}天前`;
    }
    
    // 超过30天显示具体日期
    return date.toLocaleDateString();
  }
});
